package com.bdk.middle.tenant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdk.middle.common.domain.PageDO;
import com.bdk.middle.common.result.ResultDO;
import com.bdk.middle.common.status.ErrorCode;
import com.bdk.middle.common.util.BeanUtilsExtends;
import com.bdk.middle.common.util.Constant;
import com.bdk.middle.common.util.MapTool;
import com.bdk.middle.tenant.api.client.TenantClientApi;
import com.bdk.middle.tenant.api.domain.TenantDO;
import com.bdk.middle.tenant.api.domain.TenantReviewCommentDO;
import com.bdk.middle.tenant.api.domain.TenantUserDO;
import com.bdk.middle.tenant.api.query.TenantQueryDO;
import com.bdk.middle.tenant.api.vo.TenantReviewCommentVO;
import com.bdk.middle.tenant.core.entity.TenantEntity;
import com.bdk.middle.tenant.core.entity.TenantReviewCommentEntity;
import com.bdk.middle.tenant.core.mapper.TenantMapper;
import com.bdk.middle.tenant.core.mapper.TenantReviewCommentMapper;
import com.bdk.middle.tenant.service.TenantRoleService;
import com.bdk.middle.tenant.service.TenantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdk.middle.tenant.service.TenantUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2021-03-09
 */
@RestController
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, TenantEntity> implements TenantService, TenantClientApi {


    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private TenantReviewCommentMapper tenantReviewCommentMapper;
    @Autowired
    private TenantUserService tenantUserService;
    @Override
    public ResultDO add(TenantDO domain) {
        TenantEntity entity = new TenantEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        //租户用户账号和密码不能为空
        if(domain.getUsername()==null||domain.getPassword()==null)
        {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TENANT_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.TENANT_ADD_ERROR.getCode() + " msg" + ErrorCode.TENANT_ADD_ERROR.getMsg());
            return result;
        }

        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setCreateDate(Calendar.getInstance().getTime());
        entity.setModifiDate(entity.getCreateDate());
        entity.setModifier(entity.getCreator());

        int res = -1;
        try {
            res = tenantMapper.insert(entity);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TENANT_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.TENANT_ADD_ERROR.getCode() + " msg" + ErrorCode.TENANT_ADD_ERROR.getMsg());
            return result;
        }
        //租户用户添加用户名和密码
        if(domain.getUsername()!=null&&domain.getPassword()!=null)
        {
            TenantUserDO userDO =new TenantUserDO();
            userDO.setTenantId(entity.getId());
            userDO.setUsername(domain.getUsername());
            userDO.setPassword(domain.getPassword());
            result=tenantUserService.add(userDO);
        }

        return result;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDO edit(TenantDO domain) {

        TenantEntity entity = new TenantEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        entity.setModifiDate(Calendar.getInstance().getTime());

        int res = -1;
        try {
            res = tenantMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TENANT_EDIT_ERROR);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.debug("error code：" + ErrorCode.TENANT_EDIT_ERROR.getCode() + " msg" + ErrorCode.TENANT_EDIT_ERROR.getMsg());
            return result;
        }
        return result;
    }
    @Override
    public ResultDO get(String id) {
        ResultDO result = new ResultDO();

        TenantEntity entity = null;

        try {
            entity = tenantMapper.selectById(id);
        } catch(Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        TenantDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDO check(TenantReviewCommentDO domain) {
        ResultDO result = new ResultDO();
        TenantEntity entity = new TenantEntity();
        entity.setId(domain.getTenantId());
        entity.setStatus(domain.getStatus());
        entity.setModifiDate(Calendar.getInstance().getTime());
        int res = -1;
        try {
            res = tenantMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TENANT_EDIT_ERROR);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.debug("error code：" + ErrorCode.TENANT_EDIT_ERROR.getCode() + " msg" + ErrorCode.TENANT_EDIT_ERROR.getMsg());
            return result;
        }

        res = -1;
        if(domain.getStatus() == Constant.NOT_PASS) {
            TenantReviewCommentEntity entity1 = new TenantReviewCommentEntity();
            entity1.setTTenantId(domain.getTenantId());
            entity1.setComment(domain.getComment());
            entity1.setCreateDate(Calendar.getInstance().getTime());
            entity1.setModifiDate(entity1.getCreateDate());
            try {
                res = tenantReviewCommentMapper.insert(entity1);
            } catch (Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }

            //判断r的值是否小于0.如果小于0 就代表添加失败
            if(res < 0) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.TENANT_EDIT_ERROR);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                logger.debug("error code：" + ErrorCode.TENANT_CHECK_ERROR.getCode() + " msg" + ErrorCode.TENANT_CHECK_ERROR.getMsg());
                return result;
            }
        }

        return result;
    }
    @Override
    public ResultDO remove(String id, String modifier) {

        ResultDO result = new ResultDO();

        TenantEntity entity = new TenantEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setId(id);
        entity.setIsDelete(Constant.IS_DELETE);

        int res = -1;
        try {
            res = tenantMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TENANT_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.TENANT_DELETE_ERROR.getCode() + " msg" + ErrorCode.TENANT_DELETE_ERROR.getMsg());
            return result;
        }

        return result;
    }
    @Override
    public ResultDO find(TenantQueryDO query) {

        TenantEntity entity = new TenantEntity();

        ResultDO result = BeanUtilsExtends.copy(entity,query);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<TenantEntity> wrapper = new QueryWrapper<TenantEntity>(entity);
        if(StringUtils.isNotEmpty(query.getName())) {
            wrapper.like("name", query.getName());
        }
        if(StringUtils.isNotEmpty(query.getTelephone())) {
            wrapper.like("telephone", query.getTelephone());
        }
        wrapper.eq("is_delete", Constant.IS_DELETE_FALSE);

        Page<TenantEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<TenantEntity> iPage = null;
        try {
            iPage = tenantMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<TenantDO> doList = getDomainList(iPage.getRecords());

        PageDO<TenantDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }
    @Override
    public ResultDO findTenantMultiReview(TenantReviewCommentVO query) {

        TenantEntity entity = new TenantEntity();

        ResultDO result = BeanUtilsExtends.copy(entity,query);

        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
//        QueryWrapper<TenantReviewCommentVO> wrapper = new QueryWrapper<TenantReviewCommentVO>();
//        if(StringUtils.isNotEmpty(query.getName())) {
//            wrapper.like("t.name", query.getName());
//        }
//        if(StringUtils.isNotEmpty(query.getTelephone())) {
//            wrapper.like("t.telephone", query.getTelephone());
//        }
//        wrapper.eq("t.is_delete", Constant.IS_DELETE_FALSE);


        Page<Map<String, String>> page = new Page<>(query.getCurrentPage(),query.getPageSize());

        IPage<Map<String, Object>> iPage = null;

        Map<String, Object> param = new HashMap<>();
        if(StringUtils.isNotEmpty(query.getName())) {
            param.put("name", query.getName());
        }
        if(StringUtils.isNotEmpty(query.getTelephone())) {
            param.put("telephone", query.getTelephone());
        }
            param.put("is_delete", Constant.IS_DELETE_FALSE);

        try {
            iPage = tenantMapper.getTenantReviewComment(page, param);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

//        List<TenantReviewCommentVO> doList = getDomainList(iPage.getRecords());

        List<TenantReviewCommentVO> doList = iPage.getRecords().stream().map(m->{
            TenantReviewCommentVO userDO = MapTool.map2Bean(m, TenantReviewCommentVO.class,true);
            return userDO;
        }).collect(Collectors.toList());

        PageDO<TenantReviewCommentVO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    private TenantDO getDomain(TenantEntity entity) {
        ResultDO result = new ResultDO();
        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        TenantDO domain = new TenantDO();

        if(!result.isSuccess()) {
            return null;
        }
        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private  List<TenantDO> getDomainList(List<TenantEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<TenantDO> doList = new ArrayList<>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(TenantEntity entity : list) {

                TenantDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
}
